<template>
  <section>
    <!--工具条 高级查询位置-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keywords" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordsQuery">关键字查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!-- :data="department"  绑定的数据
            highlight-current-row 高亮显示
            v-loading="listLoading" 忙等框
            @selection-change="selsChange"  勾选复选框触发事件
            sortable  排序
            :formatter="formatSex" 操作单选框的事件
    -->
    <el-table :data="roles" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="35">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="150" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="编码" width="150" sortable>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页栏工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
      </el-pagination>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增和编辑对话框-->
    <el-dialog :title="title"  :visible.sync="editFormVisible" :close-on-click-modal="false">
      <!--ref="editForm" 指定表单名称，以后可以通过this.$refs.roleForm-->
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="分配菜单" prop="menus">
          <el-cascader v-model="editForm.menus" clearable
                       placeholder="请选择"
                       :options="menuTree"
                       :props="{
									multiple: true,
								 	label:'name',
									value:'id'
								 }"
                       filterable></el-cascader>
        </el-form-item>
        <!--
         :label: 页面展示的数据
         :value： 向后台传的值
         -->
        <el-form-item label="分配权限" prop="permissions">
          <el-select v-model="editForm.permissions" multiple placeholder="请选择">
            <el-option
                v-for="item in permissionList"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">保存</el-button>
      </div>
    </el-dialog>
  </section>
</template>


<script>

export default {
  data() {
    return {
      //高级查询所需数据
      keywords: null,
      
      //权限列表
      permissionList:[],
      //菜单树-级联
      menuTree:[],
      
      //分页显示所属数据
      roles: [],
      totals: 0,
      currentPage: 1,
      pageSize: 5,
      listLoading: false,

      //多条数据选中
      sels: [],//列表选中列

      //添加或修改数据
      title:'',
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,

      //表单校验规则
      editFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ],
        menus: [
          { required: true, message: '请分配菜单', trigger: 'blur' }
        ],
        permissions: [
          { required: true, message: '请分配权限', trigger: 'blur' }
        ],
      },
      
      //编辑界面数据
      editForm: {
        id: null,
        name: '',
        sn: '',
        menus: null,
        permissions: null
      },

    }
  },
  methods: {
    //关键字查询
    keywordsQuery(){
      //页码改成1
      this.currentPage = 1;
      this.getRole();
    },

    //分页查询 - 点击某一页查询
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      //重新发送请求
      this.getRole();
    },

    //获取角色列表
    getRole(){
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keywords: this.keywords  //高级查询才用
      };

      //开启忙等框
      this.listLoading = true;
      //发送请求  axios 需要配置axios全局
      this.$http.post("/role", para)
          .then(res => {  //res: PageList: {totals:xx, rows: xx}

            //关闭忙等框
            this.listLoading = false;

            this.roles = res.data.rows;
            this.totals = res.data.totals;

          }).catch(res =>{
        this.$message.error('系统繁忙,稍后重试');
      })

    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {//点击确认按钮
        this.listLoading = true;//忙等框

        //发送请求
        this.$http.delete("/role/"+row.id)
            .then(res=>{

              this.listLoading = false;//关闭忙等框

              if(res.data.success){
                this.$message({
                  message: '删除成功',
                  type:'success'
                });

              }else {
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
              //重新发送请求,刷新页面  
              this.getRole();

            }).catch(res=>{
          this.$message({
            message: '系统繁忙,稍后重试',
            type: 'error'
          });
        });
      }).catch(() => {//点击取消
        this.$message.error('系统繁忙,稍后重试');
        type:'error'
      });
    },
    
    //显示编辑界面
    handleEdit: function (index, row) {
      //修改对话框标题
      this.title = "编辑";
      //回显
      this.editForm = Object.assign({}, row);

      this.getMenuTree();//加载菜单树
      this.getPermissionList();//加载权限下拉列表

      if(row.ownMenus){//需要回显，这里要处已经拥有的权限的格式
        let menus = [];
        for(let i=0;i<row.ownMenus.length;i++){
          let menu = row.ownMenus[i];
          let menuTmp = [];
          if(menu.parent_id != null && menu.parent_id != ""){
            menuTmp.push(menu.parent_id);
          }
          menuTmp.push(menu.id);
          menus.push(menuTmp);
        }
        this.editForm.menus = menus;
      }
      //弹出对话框
      this.editFormVisible = true;
    },
    
    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.getMenuTree();//加载菜单树
      this.getPermissionList();//加载权限下拉列表
      
      //清空模态框
      this.editForm= {
        id: null,
        name: '',
        sn: '',
        menus: null,
        permissions: null,
      },
      //弹出模态框
      this.editFormVisible = true;
    },
    
    //编辑
    //提交按钮
    editSubmit: function () {
      //表单校验:valid是一个布尔值,当校验成功为true,进入到if循环
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认保存吗？', '提示', {}).then(() => {
            this.editLoading = true;
            let para = Object.assign({}, this.editForm);
            //处理分配菜单参数格式 menus:[[22,23],[22,24],[22,25]]---->menus:[23,24,25]
            let menusArr = para.menus;
            if (menusArr) {
              let menusTmp = [];
              for (var i = 0; i < menusArr.length; i++) {
                let menuTmp = menusArr[i];
                menusTmp.push(menuTmp[menuTmp.length - 1]);
              }
              para.menus = menusTmp;
            }
            this.$http.put("/role", para).then((res) => {
              this.editFormVisible = false;
              this.editLoading = false;
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();//重置表单

              } else {
                this.$message.error("操作失败【500】");
              }
              this.getRoles(); //重新加载
            }).catch(res => {
              this.$message({
                message: '系统异常,稍后重试',
                type: 'error'
              });
            })
          });
        }
      });
    },

    //多选框
    selsChange: function (sels) {
      this.sels = sels;
      //console.debug(sels)
    },

    //批量删除
    batchRemove: function () {

      var ids = this.sels.map(item => item.id);  // [1,2,3,4,5,6]

      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; // 开启忙等框

        //patch:批量操作的请求
        this.$http.patch("/role",ids)
            .then(res=>{
              // 关闭忙等框
              this.listLoading = false;
              if(res.data.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
              this.currentPage = 1;
              this.getRole();
            }).catch(res=>{
          this.$message({
            message: '系统异常，稍后重试',
            type: 'error'
          });
        })
      }).catch(() => {

      });
    },
    
    //获取菜单树 - 无线级联
    getPermissionList(){
      this.$http.get("/permission").then(res => {
        if(res.data){
          this.permissionList = res.data;
        }
      });
    },

    //获取菜单树 - 无线级联
    getMenuTree(){
      this.$http.get("/menu/menuTree").then(res => {
        if(res.data){
          this.menuTree = res.data;
        }
      });
    }
    
  },

  //钩子函数:页面加载方法
  mounted() {
    this.getRole();
  }
}

</script>

<style scoped>

</style>